package fr.umlv.m2.recipes.ideas.parser;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.res.XmlResourceParser;
import fr.umlv.m2.recipes.ideas.bean.IngredientBean;
import fr.umlv.m2.recipes.ideas.bean.KeywordBean;
import fr.umlv.m2.recipes.ideas.bean.RecipeBean;
import fr.umlv.m2.recipes.ideas.bean.RecipeToIngredientBean;
import fr.umlv.m2.recipes.ideas.bean.RecipeToKeywordBean;
import fr.umlv.m2.recipes.ideas.bean.StepBean;
import fr.umlv.m2.recipes.ideas.features.RecipeGroupFeatures;

/**
 * Define a Parser to filter an XML file
 * @author Christophe Chillan
 *
 */
public class Parser {
	private static final Parser parserInstance = new Parser();
	private static final RecipeGroupFeatures recipesFeatures = new RecipeGroupFeatures();
	private static final String defaultPictureLink = "drawable/default_recipe";
	private Parser() {
	}

	/**
	 * Get the instance of the parser
	 * @return the Singleton instance of the {@link Parser}
	 */
	public static Parser getInstance() {
		return parserInstance;
	}
	
	/**
	 * Get all the parsed Element 	
	 * @param resource
	 * @return a {@link RecipeGroupFeatures} to manipulate all the datas
	 */
	public static RecipeGroupFeatures getAllParsedRecipes(XmlResourceParser resource){
		if(recipesFeatures.getRecipes().size()>0){
			return recipesFeatures;
		}else{
			try {
				
				String tagName = new String();
				
				int index=-1;
				boolean waitForDescription=false;
				boolean waitForSteps=false;
				StepBean currentStepBean = new StepBean();
				while(resource.getEventType() != XmlPullParser.END_DOCUMENT){
					if (resource.getEventType() == XmlPullParser.START_TAG) {
						tagName = resource.getName();
						if(tagName.equals("recipe")){//pour toutes les recipes
							recipesFeatures.addRecipeBean(++index,new RecipeBean());
							recipesFeatures.getRecipes().get(index).setName(resource.getAttributeValue(null,"name"));
							recipesFeatures.getRecipes().get(index).setDifficulty(Integer.parseInt(resource.getAttributeValue(null,"difficulty")));
							String pictureLink = (resource.getAttributeValue(null,"pictureLink")!=null)?resource.getAttributeValue(null,"pictureLink"):defaultPictureLink;
							int vote = (resource.getAttributeValue(null,"vote")==null)?0:Integer.parseInt(resource.getAttributeValue(null,"vote"));
							recipesFeatures.getRecipes().get(index).setVotes(vote);
							recipesFeatures.getRecipes().get(index).setPictureLink(pictureLink);
						}
						
						if(tagName.equals("description")){//pour pouvoir entrer une description d'une recette (recipe)
							waitForDescription=true;
						}
						
						if(tagName.equals("keywords")){//pour les mots-clés d'une recette (recipe)
							String s = resource.getAttributeValue(null, "value");
							String[] result = s.split(",");
							for(String keyword : result){
								int keywordId = (recipesFeatures.getKeywordFields().get(keyword)==null)?recipesFeatures.getKeywords().size()+1:recipesFeatures.getKeywordFields().get(keyword);
								recipesFeatures.putKeywordBean(new KeywordBean(keyword, keywordId), keywordId);
								recipesFeatures.addRecipeToKeyword(new RecipeToKeywordBean((index+1), keywordId));
							}
						}
				
						
						if(tagName.equals("ingredient")){//pour les ingredients d'une recette (recipe)
							String name = resource.getAttributeValue(null, "name");
							Integer ingredientId = recipesFeatures.getIngredientFields().get(name);
							if(ingredientId==null){
								ingredientId = recipesFeatures.getIngredients().size()+1;
							}
							IngredientBean ingredient = new IngredientBean(name,ingredientId);
							
							String priceText = (resource.getAttributeValue(null,"price")!=null)?resource.getAttributeValue(null,"price"):"0";
							if(priceText != null){
								ingredient.setPrice(Float.parseFloat(priceText));
							}
							recipesFeatures.putIngredientBean(ingredient, ingredientId);
							recipesFeatures.addRecipeToIngredient(new RecipeToIngredientBean((index+1),ingredientId));
						}
						
						
						if(tagName.equals("steps")){//pour gerer toutes les etapes (surtout leur description) d'une recette (recipe)
							waitForSteps=true;
						}
						
						if(tagName.equals("step")){// pour une etape d'une recette (recipe)
							String name = resource.getAttributeValue(null, "name");
							int currentStepId = recipesFeatures.getSteps().size()+1;
							currentStepBean = new StepBean(name, currentStepId, (index+1));
							currentStepBean.setDuration(Integer.parseInt(resource.getAttributeValue(null, "duration")));
							recipesFeatures.addStepBean(currentStepBean);
							
						}
						
						
					}else if(resource.getEventType()== XmlPullParser.TEXT){
						if(waitForDescription){// pour la description d'une recette (recipe)
							recipesFeatures.getRecipes().get(index).setDescription(resource.getText());
							waitForDescription=false;
						}
						if(waitForSteps && currentStepBean.getDescription()==null){//pour la description d'une etape (step) d'une recette (recipe)
							currentStepBean.setDescription(resource.getText());
						}
					}else if(resource.getEventType() == XmlPullParser.END_TAG){
						
						if(tagName.equals("steps")){
							waitForSteps=false;
						}
					}
					
					resource.next();
				}
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return recipesFeatures;
		}
	}
	
	

	
}


